<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" :size="size">
                <el-row v-if="!shopId">
                    <el-col :span=6>
                        <el-form-item label="门店名称" prop="shopName">
                            <el-input v-model="condition.search.shopName"
                                      placeholder="门店名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="门店ID" prop="shopId">
                            <el-input v-model="condition.search.shopId"
                                      placeholder="门店ID"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="门店UUID" prop="shopUuid">
                            <el-input v-model="condition.search.shopUuid"
                                      placeholder="门店UUID"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="同步日期" prop="syncDate">
                            <el-date-picker
                                v-model="condition.search.syncDate"
                                type="date"
                                placeholder="同步日期"
                                value-format="yyyy-MM-dd"
                                align="right">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item v-if="!shopId">
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item v-if="!shopId">
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="exportExcel">导出</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button v-if="showChange" type="success" @click="showChange = false">不显示变化
                            </el-button>
                            <el-button v-else type="warning" @click="showChange = true">显示变化</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="warning" @click="downloadReport" v-if="shopId">下载日报</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            :size="size"
            id="dpShopMainTable"
            :data="tableData"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="60">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="shopName"
                width="100px"
                label="门店名称">
                <template v-slot="scope">
                    <a :href="scope.row.shopUrl" target="_blank">
                        {{ scope.row.shopName }}
                    </a>
                </template>
            </el-table-column>
            <el-table-column
                prop="syncDate"
                label="数据日期">
            </el-table-column>
            <el-table-column
                prop="avgPrice"
                label="人均">
                <template v-slot="scope">
                    <badge :current="scope.row.avgPrice" :change="scope.row.avgPriceChange" :show="showChange"></badge>
                </template>
            </el-table-column>
            <el-table-column
                prop="rankNameEx"
                width="120px"
                label="榜单">
            </el-table-column>
            <el-table-column
                prop="mainScore"
                label="大分">
                <template v-slot="scope">
                    <badge :current="scope.row.mainScore" :change="scope.row.mainScoreChange"
                           :show="showChange"></badge>
                </template>
            </el-table-column>
            <el-table-column
                prop="tasteScore"
                label="口味分">
                <template v-slot="scope">
                    <badge :current="scope.row.tasteScore" :change="scope.row.tasteScoreChange"
                           :show="showChange"></badge>
                </template>
            </el-table-column>
            <el-table-column
                prop="envScore"
                label="环境分">
                <template v-slot="scope">
                    <badge :current="scope.row.envScore" :change="scope.row.envScoreChange" :show="showChange"></badge>
                </template>
            </el-table-column>
            <el-table-column
                prop="serviceScore"
                label="服务分">
                <template v-slot="scope">
                    <badge :current="scope.row.serviceScore" :change="scope.row.serviceScoreChange"
                           :show="showChange"></badge>
                </template>
            </el-table-column>
            <el-table-column
                prop="foodScore"
                label="食材分">
                <template v-slot="scope">
                    <badge :current="scope.row.foodScore" :change="scope.row.foodScoreChange"
                           :show="showChange"></badge>
                </template>
            </el-table-column>
            <el-table-column
                prop="picCount"
                label="图片数量">
                <template v-slot="scope">
                    <badge :current="scope.row.picCount" :change="scope.row.picCountChange" :show="showChange"></badge>
                </template>
            </el-table-column>
            <el-table-column
                prop="reserveCount"
                label="预定数量">
                <template v-slot="scope">
                    <badge :current="scope.row.reserveCount" :change="scope.row.reserveCountChange"
                           :show="showChange"></badge>
                </template>
            </el-table-column>
            <el-table-column
                prop="reviewCount"
                label="评论数量">
                <template v-slot="scope">
                    <badge :current="scope.row.reviewCount" :change="scope.row.reviewCountChange"
                           :show="showChange"></badge>
                </template>
            </el-table-column>
            <el-table-column
                prop="favorNum"
                label="收藏数量">
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="80">
                <template v-slot="scope">
                    <div>
                        <el-button @click="downloadDailyReport(scope.row)" type="text" size="small">下载日报
                        </el-button>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small" v-if="shopId">复制新增
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px" :size="size">
                <el-form-item label="大分">
                    <el-input v-model="addOrUpdateForm.mainScore"
                              placeholder="大分"></el-input>
                </el-form-item>
                <el-form-item label="口味分">
                    <el-input v-model="addOrUpdateForm.tasteScore"
                              placeholder="口味分"></el-input>
                </el-form-item>
                <el-form-item label="环境分">
                    <el-input v-model="addOrUpdateForm.envScore"
                              placeholder="环境分"></el-input>
                </el-form-item>
                <el-form-item label="服务分">
                    <el-input v-model="addOrUpdateForm.serviceScore"
                              placeholder="服务分"></el-input>
                </el-form-item>
                <el-form-item label="食材分">
                    <el-input v-model="addOrUpdateForm.foodScore"
                              placeholder="食材分"></el-input>
                </el-form-item>
                <el-form-item label="图片数量">
                    <el-input v-model="addOrUpdateForm.picCount"
                              placeholder="图片数量"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="预定数量">
                    <el-input v-model="addOrUpdateForm.reserveCount"
                              placeholder="预定数量"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="评论数量">
                    <el-input v-model="addOrUpdateForm.reviewCount"
                              placeholder="评论数量"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="榜单名称">
                    <el-input v-model="addOrUpdateForm.rankName"
                              placeholder="榜单名称"></el-input>
                </el-form-item>
                <el-form-item label="榜单排名">
                    <el-input v-model="addOrUpdateForm.rank"
                              placeholder="榜单排名"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="同步日期">
                    <el-date-picker
                        v-model="addOrUpdateForm.syncDate"
                        type="date"
                        placeholder="同步日期"
                        value-format="yyyy-MM-dd"
                        align="right">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addOrUpdateDialogVisible = false" :size="size">取 消</el-button>
                <el-button @click="addOrUpdateConfirm" type="primary" :size="size">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="下载报表" width="40%" :visible.sync="downloadReportVisible">
            <el-form :model="downloadForm" label-width="140px" size="small">
                <el-form-item label="请选择报表类型">
                    <el-select v-model="downloadForm.reportType" placeholder="请选择" clearable>
                        <el-option label="单门店日报" value="SINGLE"></el-option>
                        <el-option label="连锁门店日报" value="MULTIPLE"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="请选择日期">
                    <el-date-picker
                        v-model="downloadForm.dateRange"
                        value-format="yyyy-MM-dd"
                        unlink-panels
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="this.CONST.analysis_date_options">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="请选择连锁门店" v-if="downloadForm.reportType === 'MULTIPLE'">
                    <el-select v-model="downloadForm.shopIdList" filterable multiple placeholder="请选择">
                        <el-option
                            v-for="item in allShops"
                            :key="item.id"
                            :label="item.shopName"
                            :value="item.shopId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否同时同步评价">
                    <el-switch v-model="downloadForm.syncFeedback"></el-switch>
                </el-form-item>
                <el-form-item>
                    <div class="form-tips">
                        时间最跨度多选择连续10天，连锁日报最多选择10家，同步连锁门店前请先确保门店的各项配置都正确，可能会耗时比较久～，如果没有连锁门店报表配置，请先联系管理员～
                        <br/>
                        如果日报里面有团代销量核销明细，建议先主动同步团代销量，再来点击下载报表，因为同步团代明细会很慢，尤其是团餐销量很大的店～
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="downloadReportVisible = false" size="small">取 消</el-button>
                <el-button @click="downloadReportConfirm" type="primary" size="small">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addDpShopHistory,
    deleteDpShopHistory,
    getAllShops,
    getDownloadDailyMultipleReportUrl,
    getDownloadDailyReportUrl,
    getDpShopHistoryByPage,
    updateDpShopHistory
} from '@/api/api'
import Badge from "@/component/single/Badge";
import db from "@/utils/localstorage";

export default {
    name: "dp-shop-history",
    components: {Badge},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},

            showChange: true,
            allShops: [],

            // 下载报表对话框
            downloadReportVisible: false,
            downloadForm: {
                "reportType": 'SINGLE',
                "syncFeedback": false,
            },
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        shopId: String,
        shopName: String,
        size: {
            type: String,
            default: 'small'
        },
        startDate: String,
        endDate: String,
    },
    watch: {
        startDate: function (val, oldVal) {
            this.startDate = val;
            this.getData();
        },
        endDate: function (val, oldVal) {
            this.endDate = val;
            this.getData();
        },
    },
    methods: {
        downloadReport() {
            this.downloadReportVisible = true;
            getAllShops().then(data => {
                this.allShops = data.body;
            })
        },
        downloadReportConfirm() {
            let startDate;
            let endDate;
            if (!this.downloadForm.dateRange) {
                this.$message({
                    type: 'error',
                    message: '请先选择日期!'
                });
            }
            if (this.downloadForm.reportType === 'SINGLE') {
                startDate = this.downloadForm.dateRange[0];
                endDate = this.downloadForm.dateRange[1];
                window.open(getDownloadDailyReportUrl() + "?token=" + db.getUser().token + "&shopId=" + this.shopId + "&syncFeedback=" + this.downloadForm.syncFeedback + "&startDate=" + startDate + "&endDate=" + endDate, '_blank');
                this.downloadReportVisible = false;
            } else if (this.downloadForm.reportType === 'MULTIPLE') {
                let shopIds;
                if (this.downloadForm.shopIdList.length > 0) {
                    shopIds = this.downloadForm.shopIdList.join(",")
                } else {
                    this.$message({
                        type: 'error',
                        message: '请先选择门店!'
                    });
                    return;
                }
                startDate = this.downloadForm.dateRange[0];
                endDate = this.downloadForm.dateRange[1];
                window.open(getDownloadDailyMultipleReportUrl() + "?token=" + db.getUser().token + "&shopIds=" + shopIds + "&syncFeedback=" + this.downloadForm.syncFeedback + "&startDate=" + startDate + "&endDate=" + endDate, '_blank');
                this.downloadReportVisible = false;
            }
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            console.log(row.source);
            if (row.source && row.source === 'MANUAL') {
                console.log('dddd')
                return 'manual-row';
            }
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatStatus: function (row, column, cellValue) {
            if (cellValue == '0') {
                return "关闭";
            } else if (cellValue == '1') {
                return "正常";
            } else {
                return "未知";
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '复制新增';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
            this.addOrUpdateForm.id = null;
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#dpShopMainTable', this.shopName + '每日数据统计.xlsx');
        },
        add: function () {
            addDpShopHistory(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        update: function () {
            updateDpShopHistory(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
            });
        },
        downloadDailyReport: function (row) {
            let tempDate = new Date(row.syncDate);
            // 日期减1天
            tempDate.setDate(tempDate.getDate() - 1);
            // 转为字符串
            let dateStr = tempDate.toISOString().slice(0, 10);
            // 赋值
            let startDate = dateStr;
            let endDate = dateStr;
            // 打开网页
            window.open(getDownloadDailyReportUrl() + "?token=" + db.getUser().token + "&shopId=" + row.shopId + "&startDate=" + startDate + "&endDate=" + endDate, '_blank');
        },
        onDetail: function (row) {
            this.$router.push({path: '/dp/shop/detail', query: {shopId: row.shopId}});
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteDpShopHistory({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '复制新增') {
                this.add();
            }
        },
        // 获取表格数据
        getData: function () {
            if (this.shopId) {
                this.condition.search.shopId = this.shopId;
            }
            if (this.startDate) {
                this.condition.search.startDate = this.startDate;
            }
            if (this.endDate) {
                this.condition.search.endDate = this.endDate;
            }
            getDpShopHistoryByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
            });
        },
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
